package top.huhuiyu.springboot2.util;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 日期工具类
 *
 * @author 胡辉煜
 */
public class DateUtil {

  public static final DateTimeFormatter SDF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  public static final DateTimeFormatter SDF_DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd");

  public static String format(Date date) {
    return format(date,false);
  }

  public static String format(Date date,boolean shortMode) {
    if(shortMode) {
      return SDF_DATE.format(date.toInstant().atZone(ZoneId.systemDefault()));
    }
    return SDF.format(date.toInstant().atZone(ZoneId.systemDefault()));
  }

  public static Date parse(String date) {
    try {
      return Date.from(LocalDateTime.parse(date, SDF).atZone(ZoneId.systemDefault()).toInstant());
    } catch (Exception ex) {
      return Date.from(LocalDateTime.parse(date + " 00:00:00", SDF).atZone(ZoneId.systemDefault()).toInstant());
    }
  }

}
